import React, { useEffect, useState } from 'react';
import { Button, Form } from 'antd';
import styles from './index.less';
import { debounce } from 'lodash';

const DRBox = ({
  formType,
  viewRecord,
  handleComponentInit,
  handleCreateSubmit,
  handleAfterFormReset,
  handleReset,
  children,
  onInstanceClose,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    handleComponentInit && handleComponentInit(form);
  }, []);

  useEffect(() => {
    if (handleReset === true) {
      form?.resetFields();
    }
  }, [handleReset]);

  const handleFormSubmit = debounce(async (formValue) => {
    setLoading(true);
    if (formType === 'create') {
      await handleCreateSubmit(formValue);
      setLoading(false);
    }
    if (formType === 'edit') {
      const newFormValue = { ...formValue, formType };
      await handleCreateSubmit(newFormValue);
      setLoading(false);
    }
  }, 1000);

  const handleFormReset = () => {
    form?.resetFields();
    handleCreateSubmit && handleCreateSubmit(form?.getFieldsValue());
    handleAfterFormReset && handleAfterFormReset();
  };

  return (
    <div className={styles.box}>
      <div className={styles.content}>
        <Form layout="vertical" form={form} onFinish={handleFormSubmit} className={styles.form}>
          <div className={styles.select}>{children(form)}</div>
          {/* {viewRecord?.id ? (
            <div className={styles.buttonBox}>
              <div className={styles.serchButton}>
                <Button type="" onClick={onInstanceClose}>
                  返回
                </Button>
              </div>
            </div>
          ) : null} */}
          <div>
            {formType === 'view' || formType === 'instanceView' ? null : (
              <Form.Item>
                <div className={styles.buttonBox}>
                  <div className={styles.serchButton}>
                    <Button type="primary" htmlType="submit" loading={loading}>
                      提交
                    </Button>
                  </div>
                  {/* <div className={styles.serchButton}>
                    <Button onClick={() => handleFormReset()}>重置</Button>
                  </div> */}
                </div>
              </Form.Item>
            )}
          </div>
        </Form>
      </div>
    </div>
  );
};
export default DRBox;
